package com.XZDP.Interceptor;

import cn.hutool.core.bean.BeanUtil;
import com.XZDP.dto.UserDTO;
import com.XZDP.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.util.Map;

//全局拦截器用于刷新token,放行一切
public class FlushedInterceptor implements HandlerInterceptor {
    private StringRedisTemplate redisTemplate;

    public FlushedInterceptor(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        String token = request.getHeader("authorization");
        //token判空
        if (token == null) {
            return true;
        }
        //从redis读取数据
        Map<Object, Object> UserMap = redisTemplate.opsForHash().entries("User:" + token);
        //判断是否有用户
        if (UserMap.isEmpty()) {
            return true;
        }
        //将查询到的HushMap转换回UserDTO对象
        UserDTO userDTO = BeanUtil.fillBeanWithMap(UserMap, new UserDTO(), false);
        //存在用户将用户存入线程
        UserHolder.saveUser(userDTO);
        //刷新过期时间
        redisTemplate.expire("User:" + token, Duration.ofHours(2));
        //放行
        return true;
    }


    //释放用户
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
